package xyz.xtgl.security.springboot.dao;

import xyz.xtgl.security.springboot.entity.Permission;
import xyz.xtgl.security.springboot.entity.User;
import common.core.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @created 2019-12-16 22:34
 */
@Slf4j
@Repository
public class UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public User getUserByusername(String username){
        log.info("getUserByusername->根据用户名获取用户:{}",username);
        String sql = "select  *  from t_user where username =? ";
        List<User> list = jdbcTemplate.query(sql, new String[]{username} ,new BeanPropertyRowMapper<>(User.class));
        if(CommonUtil.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }

    public List<String> findPermissionsByUserId(Long userId){
        log.info("findPermissionsByUserId()->根据用户ID获取权限:{}",userId);
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT ");
        sql.append("    * ");
        sql.append(" FROM ");
        sql.append("    t_permission a ");
        sql.append("    INNER JOIN t_role_permission b ON a.id = b.permission_id ");
        sql.append("    INNER JOIN t_user_role c ON b.role_id = c.role_id ");
        sql.append(" WHERE ");
        sql.append("    c.user_id =? ");
        List<Permission> list = jdbcTemplate.query(sql.toString(),new Long[]{userId},new BeanPropertyRowMapper<>(Permission.class));
        List<String> result = new ArrayList<>();
        list.forEach(row->result.add(row.getCode()));
        return result;
    }
}
